//
//  HomeViewController.swift
//  BaseSwift
//
//  Created by ghwang on 2019/7/22.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import EasyNavigation
import PYSearch


class HomeViewController: UIViewController {

    private var displayLabel:UILabel = UILabel()
    private let searTf = UITextField()
    private var lastMenuBtn:UIButton?
    private var coord:CLLocationCoordinate2D?
    private var mapview:MKMapView?
    private var currintTag = 0
    private var currentArr:Array<LSListAnnotation> = Array()
    private var currentID:String = ""
    private var moreBtn:UIButton = UIButton()
    
    private var  products:Array<ProductVo> = Array()
    private var  scenices:Array<ScenicVo> = Array()

    private var  classy:Array<Classisy> = Array()
    private var dataArray:Array<Any> = Array()
    private var categorys:Array<CategoryVo> = Array()

    private var curClassisy:Classisy?
    
    private var distance:Double = 0.00
    private var isShowedMap = false
    
    let searBtn = UIButton()
    let userBtn = UIButton()
    
    private var isNeedReloadData = true
    private var curAnn:LSListAnnotation?
    var isHaveMore = true

    var pageIndex = 1
    var firstMod:CategoryVo?
    
    var curMod:CategoryVo?
    
    var keywords = ""
    var clearBtn: UIButton?
    var viewsArr: Array<UIView> = Array()
    var isClickPlace = false
    var isClickSearch = false



    func getCategorys(){
        
        
        API.home_category(params: [:]) { (result) in
            
            self.classy = result as! Array<Classisy>
            self.curClassisy = self.classy.first

            self.reloadMapMenus()
            
            self.sendRequestForCategory(isShowAlert: true)
            
        }
    }
    
    func getActivisGoods() -> Array<ActivisProduct>{
        
        if SPUtil.init().activits == nil {
            
            return []
        }
        let list: [ActivisProduct] = [ActivisProduct].deserialize(from:SPUtil.init().activits)! as! [ActivisProduct]
        return list
    }
    
    func sendRequestForCategory(isShowAlert:Bool){
        
        if self.isLocationServiceOpen() == true {
            
            ToastUtil.showAlert(context: self, title: "提示", msg: "好去处需要获得您的位置授权，才能正常使用地图功能。请您手动在设置页面授权") {
                
                let appSettings = NSURL(string: UIApplication.openSettingsURLString)
                UIApplication.shared.openURL(appSettings! as URL)
            }
            return
        }
        
        API.home_category_list(params: ["startLong":self.coord!.longitude.description,
                                        "startLat":self.coord!.latitude.description,
                                        "distance":"200000",
                                        "page":self.pageIndex.description,
                                        "type":curClassisy!.type!,
                                        "keyWord":self.keywords],isSlience: false) { (result) in
                                            
                                            
            
                                            let page = result as! Page<CategoryVo>
                                                                            
                                            self.isHaveMore = page.hasNextPage

                                            if self.pageIndex == 1{
                                                
                                                self.categorys = page.list

                                            }else{
                                                
                                                for item in page.list{
                                                    
                                                    self.categorys.append(item)
                                                }
                                            }
                                            
                                            //chanage
                                            if self.categorys.count == 0{
                                                
                                                if isShowAlert == true {
                                                    
                                                    ToastUtil.showAlert(context: self, title: "提示", msg: "未检索到\(self.keywords)相关信息")
                                                }


                                                self.mapview?.removeAnnotations(self.currentArr)
                                                self.bbbg.isHidden = true
                                                self.mapbg?.isHidden = true
                                                let _ = self.mapview?.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 44, left: 0, bottom: 25, right: 0))
                                                self.mapview?.updateLayout()

                                                
                                                

                                               //拼接活动产品
                                               let actis = self.getActivisGoods()
                                               actis.forEach { (item) in
                                                   
                                                   let tempCate = CategoryVo()
                                                   tempCate.isActivity = true
                                                   tempCate.proName = item.title
                                                   tempCate.proAddress = item.context
                                                   tempCate.latitude = item.latitude
                                                   tempCate.longitude = item.longitude
                                                   tempCate.iconUrl = item.icon
                                                   tempCate.posterImg = item.icon
                                                   tempCate.pdtId = item.pdtId
                                                   
                                                   self.categorys.append(tempCate)
                                                   
                                               }
                                               
                                               var anns = Array<CategoryVo>()
                                               self.categorys.forEach { (item) in
                
                                                   anns.append(item)
                                                   
                                               }

                                                self.firstMod = nil
                                                self.showAntions(arr: anns)

                                                return
                                            }
                                            
                                            self.bbbg.isHidden = false
                                            self.mapbg?.isHidden = false
                                            let _ = self.mapview?.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 44, left: 0, bottom: 25+135, right: 0))
                                            self.mapview?.updateLayout()
                                            self.reloadMapCards(arr:self.categorys)
            

                                            //拼接活动产品
                                            let actis = self.getActivisGoods()
                                            actis.forEach { (item) in
                                                
                                                let tempCate = CategoryVo()
                                                tempCate.isActivity = true
                                                tempCate.proName = item.title
                                                tempCate.proAddress = item.context
                                                tempCate.latitude = item.latitude
                                                tempCate.longitude = item.longitude
                                                tempCate.iconUrl = item.icon
                                                tempCate.posterImg = item.icon
                                                tempCate.pdtId = item.pdtId
                                                
                                                self.categorys.append(tempCate)
                                                
                                            }
                                            
                                            var anns = Array<CategoryVo>()
                                            self.categorys.forEach { (item) in
             
                                                anns.append(item)
                                                
                                            }
                                            

                                            
                                            self.firstMod = nil
                                            self.showAntions(arr: anns)
                                                //scr 滚动
                                            self.mapbg?.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
                                            
                                            
                                            
        }
        
    }
    
    func sendRequest() {
        
        API.home_recom_goods(params: [:]) { (result) in
            
            let page = result as! Page<ProductVo>
            self.products = page.list
            
            if self.products.count < 5{
                
                self.products.forEach { (item) in
                    
                    self.dataArray.append(item)

                }
                
            }else{
                
                for index in 0 ..< 5{
                    
                    self.dataArray.append(self.products.get(at: index) as Any)

                }

            }
            


            
            API.home_topic(params: [:]) { (result) in
                
                let page = result as! Page<TopPic>
                
                let modd = self.dataArray.get(at: 1)
                if modd is Array<TopPic>{
                    
                    self.dataArray.remove(at: 1)
                }

                if page.list.count > 0{
                    
 
                    self.dataArray.insert(page.list, at: 1)
                    
                    self.homeTableView.reloadData()
                }

            }
            

        }

        API.home_line(params: [:]) { (result) in
            
            let page = result as! Page<RouteVo>
            if page.list.count < 5{
                
                page.list.forEach { (item) in
                    
                    
                    self.dataArray.append(item)
                }
            }else{
                
                for index in 0 ..< 5{
                    
                    self.dataArray.append(page.list.get(at: index) as Any)

                }
            }

            API.home_recom_scenics(params: [:]) { (scenics) in
                
                   let page = scenics as! Page<ScenicVo>
                   self.scenices = page.list
                   
                   if self.scenices.count < 5{
                       
                       self.scenices.forEach { (item) in
                           
                           self.dataArray.append(item)

                       }
                       
                   }else{
                       
                       for index in 0 ..< 5{
                           
                           self.dataArray.append(self.scenices.get(at: index) as Any)

                       }

                   }
                
                self.homeTableView.reloadData()

            }        }

        
    }
    
    lazy var contentView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 2*self.view.sd_height)
        return bg
    
    }()
    
    
    lazy var homeTableView:UITableView = {
        
        let tableView = UITableView(frame: CGRect(x: 0, y: self.view.sd_height+HT_StatusBarAndNavigationBarHeight, width: KScreenWidth, height: view.sd_height-HT_StatusBarAndNavigationBarHeight), style:.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorColor = .clear
        tableView.backgroundColor = UIColor.white
        tableView.contentSize = CGSize(width: KScreenWidth, height: view.height+1)
        tableView.register(UINib(nibName: "LineCell", bundle: nil), forCellReuseIdentifier: "LineCell")
        tableView.register(UINib(nibName: "WeSocialCell", bundle: nil), forCellReuseIdentifier: "WeSocialCell")
        tableView.register(UINib(nibName: "GoodsCell", bundle: nil), forCellReuseIdentifier: "GoodsCell")
        tableView.showsVerticalScrollIndicator = false

        tableView.addSubview(displayLabel)
        //tableView.tableHeaderView = self.tableHeaderView
        tableView.tableFooterView = UIView()
        self.displayLabel.frame = CGRect(x: 0,y: -40, width: KScreenWidth, height: 30)
        self.displayLabel.textColor = UIColor.textTitleColor
        self.displayLabel.font = UIFont.commonFontSmaller
        self.displayLabel.textAlignment = .center
        
        return tableView
        
    }()
    
    lazy var twoFloorView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: HT_StatusBarAndNavigationBarHeight, width: KScreenWidth, height: self.view.sd_height-HT_TabbarSafeBottomMargin-HT_StatusBarAndNavigationBarHeight)
        bg.backgroundColor = UIColor.white
        let pullBtn = UIButton()
        pullBtn.setTitle("点击返回首页", for: .normal)
        pullBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
        pullBtn.addTarget(self, action: #selector(pullClick), for: .touchUpInside)
        pullBtn.titleLabel?.font = UIFont.smallFont
        bg.addSubview(pullBtn)
        
        let _ = pullBtn.sd_layout()?.widthRatioToView(bg,1)?.bottomSpaceToView(bg,0)?.heightIs(25)
        

        //map
        self.mapview = MKMapView()
        bg.addSubview(self.mapview!)
        self.mapview?.delegate = self
        let _ = self.mapview?.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 44, left: 0, bottom: 25+135, right: 0))
        self.mapview?.autoresizingMask = .flexibleHeight
        self.mapview?.showsUserLocation = true
        let backUserBtn = UIButton()
        backUserBtn.addTarget(self, action: #selector(backToUser), for: .touchUpInside)
        backUserBtn.setImage(UIImage(named: "定位002"), for: .normal)
        self.mapview?.addSubview(backUserBtn)
        let _ = backUserBtn.sd_layout()?.widthIs(32)!.heightIs(32)!.leftSpaceToView(self.mapview,8)!.bottomSpaceToView(self.mapview,35)
        backUserBtn.backgroundColor = UIColor.white
        backUserBtn.sd_cornerRadius = 16
        
        

        
        return bg
        
    }()
    var scrMenuBg = UIScrollView()
    func reloadMapMenus(){
        
        //
        
        scrMenuBg.removeFromSuperview()
        scrMenuBg = UIScrollView()
        self.twoFloorView.addSubview(scrMenuBg)
        scrMenuBg.backgroundColor = UIColor.white
        let _ = scrMenuBg.sd_layout()?.leftSpaceToView(twoFloorView,12)!.heightIs(44)!.topSpaceToView(twoFloorView,0)!.rightSpaceToView(twoFloorView,12)
        for index in 0 ..< self.classy.count{
            
            let mod = self.classy.get(at: index)
            
            let menuBtn = UIButton()
            menuBtn.tag = 1900+index
            menuBtn.addTarget(self, action: #selector(mapTopMenuClick), for: .touchUpInside)
            menuBtn.frame = CGRect(x: index*58, y: 5, width: 58, height: 34)
            menuBtn.setTitle(mod?.name, for: .normal)
            menuBtn.titleLabel?.font = UIFont.commonFontSmaller
            menuBtn.setTitleColor(UIColor.init(hexString: "#999999"), for: .normal)
            scrMenuBg.addSubview(menuBtn)
            scrMenuBg.setupAutoContentSize(withRightView: menuBtn, rightMargin: 10)
            scrMenuBg.showsHorizontalScrollIndicator = false
            let icon = UIImageView()
            icon.tag = 7979
            menuBtn.addSubview(icon)
            icon.isHidden = true
            icon.sd_setImage(with: URL(string:(mod?.iconUrl!)!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                
            }
            

            if mod?.name?.count == 3 {
                
                let _ = icon.sd_layout()?.widthIs(14)!.heightIs(14)!.centerYEqualToView(menuBtn)!.rightSpaceToView(menuBtn,52)

            }else if mod?.name?.count == 4{
                
                let _ = icon.sd_layout()?.widthIs(14)!.heightIs(14)!.centerYEqualToView(menuBtn)!.rightSpaceToView(menuBtn,58)

            }
            else{
                let _ = icon.sd_layout()?.widthIs(14)!.heightIs(14)!.centerYEqualToView(menuBtn)!.rightSpaceToView(menuBtn,45)

            }

            if self.isClickPlace == true{
                
                if mod?.name == "景点"{
                    
                    self.lastMenuBtn = menuBtn
                    icon.isHidden = false

                    self.lastMenuBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.4))
                    self.lastMenuBtn!.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
                    
                }
                
            }else{
                

                if index==0 && self.keywords.count == 0{

                    icon.isHidden = false
                    self.lastMenuBtn = menuBtn
                    lastMenuBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.4))
                    lastMenuBtn!.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
                }

            }
        }
    }
    

    var  mapbg:UIScrollView?
    let bbbg = UIView()

    func reloadMapCards(arr:Array<CategoryVo>){

        
        if mapbg == nil{
            
            bbbg.frame = CGRect(x: 0, y: twoFloorView.height-135-25, width: twoFloorView.width, height: 135)

            bbbg.backgroundColor = UIColor.white
            self.twoFloorView.addSubview(bbbg)
            bbbg.clipsToBounds = true
            bbbg.SetMutiBorderRoundingCornersTLTR(bbbg, corner: 20)
            
            mapbg = UIScrollView()
            bbbg.addSubview(mapbg!)
            mapbg!.backgroundColor = UIColor.clear
            mapbg?.delegate = self
            mapbg?.clipsToBounds = false
            mapbg?.frame = CGRect(x: 20, y: 0, width: bbbg.width-40, height: 135)
            mapbg!.showsHorizontalScrollIndicator = false
            mapbg!.isPagingEnabled = true
            mapbg?.contentSize = CGSize(width: CGFloat(arr.count)*mapbg!.width, height: mapbg!.height)
            bbbg.bringSubviewToFront(mapbg!)
        }
        
        for views in mapbg!.subviews{
            
            views.removeFromSuperview()
        }

        
        for index in 0 ..< arr.count{
            
            let mod = arr.get(at: index)
            
            let cardMask = UIView()
            cardMask.backgroundColor = UIColor.clear
            cardMask.frame = CGRect(x: CGFloat(index)*(mapbg!.width)-15, y:20 , width: mapbg!.width, height: 95)
            
            cardMask.layer.shadowColor = UIColor.lightGray.cgColor
            cardMask.layer.shadowOffset = CGSize(width: 1, height: 5)
            cardMask.layer.shadowOpacity = 0.4
            


            mapbg!.addSubview(cardMask)
            mapbg!.setupAutoContentSize(withRightView: cardMask, rightMargin: 0)
            
            let subBg = UIButton()
            subBg.tag = 10086+index
            subBg.addTarget(self, action: #selector(cardMaskClick), for: .touchUpInside)
            cardMask.addSubview(subBg)
            subBg.backgroundColor = UIColor.white
            subBg.layer.cornerRadius = 8
            subBg.layer.masksToBounds = true
            let _ = subBg.sd_layout()?.leftSpaceToView(cardMask,16)!.rightSpaceToView(cardMask,16)!.topSpaceToView(cardMask,0)!.heightIs(95)
            

            
            
            
            
            
            let photo = UIImageView()
            photo.backgroundColor = UIColor.lineColor
            subBg.addSubview(photo)
            let _ = photo.sd_layout()?.widthIs(95)!.heightIs(95)!.leftSpaceToView(subBg,0)!.topSpaceToView(subBg,0)
            
            if mod?.posterImg?.starts(with: "http") == true {
                
                photo.sd_setImage(with: URL(string:(mod?.posterImg!)!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                
            }else{
                
                photo.sd_setImage(with: URL(string:"https://hqctv.oss-cn-beijing.aliyuncs.com/"+(mod?.posterImg!)!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                
            }

            let titLab = UILabel()
            titLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
            titLab.textColor = UIColor.textTitleColorBlack
            titLab.text = mod?.proName?.replacingOccurrences(of: "#", with: " ")
            subBg.addSubview(titLab)
            let _ = titLab.sd_layout()?.leftSpaceToView(photo,16)!.heightIs(20)!.topSpaceToView(subBg,10)!.rightSpaceToView(subBg,16)
            
            let infoLab = UILabel()
            infoLab.font = UIFont.commonFontSmaller
            infoLab.textColor = UIColor.textPlaceHolderColor
            infoLab.text = mod?.proAddress
            subBg.addSubview(infoLab)
            let _ = infoLab.sd_layout()?.leftSpaceToView(photo,16)!.heightIs(20)!.topSpaceToView(titLab,10)!.rightSpaceToView(subBg,16)
            
            infoLab.updateLayout()
            subBg.updateLayout()
            
            var tagss = Array<String>()
            tagss = mod!.tags!
            if (mod?.tags!.count)! >= 3 {
                
                tagss.remove(at: mod!.tags!.count-1)
                tagss.remove(at: mod!.tags!.count-2)
                tagss.remove(at: mod!.tags!.count-3)
                


            }else{
                
                tagss = mod!.tags!
            }
            if tagss.count > 0 {
                
                let tagsView = STTagsView.tagView(withFrame: CGRect(x: 14+95, y: infoLab.frame.maxY, width: 165+60, height: 15), tagsArray: tagss, textColor: UIColor.GP_Blue_Color, textFont: UIFont .systemFont(ofSize: 10), normalTagBackgroundColor: UIColor.backgroundColor, tagBorderColor: UIColor.GP_Blue_Color, contentInsets: UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5), labelContentInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3), labelHorizontalSpacing: 5, labelVerticalSpacing: 5)
                subBg.addSubview(tagsView!)
            }

        }
        
    }
    let sbg = UIView()

    lazy var searchView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.addSubview(sbg)
        let _ = sbg.sd_layout()?.widthRatioToView(bg,1)?.topSpaceToView(bg,HT_StatusBarHeight)?.bottomSpaceToView(bg,0)
        
        sbg.addSubview(userBtn)
        userBtn.setImage(UIImage(named: "默认头像"), for: .normal)
        userBtn.addTarget(self, action: #selector(meClick), for: .touchUpInside)
        let _ = userBtn.sd_layout()?.leftSpaceToView(sbg,15)?.widthIs(32)?.heightIs(32)?.centerYEqualToView(sbg)
        self.userBtn.sd_cornerRadius = 16
        if SPUtil.init().headImg != nil{
            
            if SPUtil.init().headImg.count > 0{
                
                self.userBtn.sd_setImage(with: URL(string: SPUtil.init().headImg), for: .normal, placeholderImage: UIImage(named: "默认头像"), options: .avoidDecodeImage, context: .none, progress: { (a, b, c) in
                    
                }) { (a, b, c, d) in
                    
                }
            }
        }
        
        searBtn.addTarget(self, action: #selector(startSearchClick), for: .touchUpInside)
        searBtn.setTitle("请输入目的地、线路", for: .normal)
        searBtn.titleLabel?.font = UIFont.commonFont
        searBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
        searBtn.backgroundColor = UIColor.init(hexString: "#f1f2f3")
        
        self.clearBtn = UIButton()
        self.clearBtn?.isHidden = true
        self.searBtn.addSubview(self.clearBtn!)
        self.clearBtn?.addTarget(self, action: #selector(clearBtnClick), for: .touchUpInside)
        self.clearBtn?.setImage(UIImage(named: "clear"), for: .normal)
        let _ = self.clearBtn?.sd_layout()?.widthIs(25)!.heightIs(25)!.rightSpaceToView(self.searBtn,15)!.centerYEqualToView(self.searBtn)
        
        sbg.addSubview(searBtn)
        searBtn.sd_cornerRadius = MIDDLE_BTN_RADIUS
        searBtn.setImage(UIImage(named: "search_12"), for: .normal)
        let _ = searBtn.imageView?.sd_layout()?.heightIs(16)!.widthIs(16)!.rightSpaceToView(searBtn.titleLabel,3)
        let _ = searBtn.sd_layout()?.leftSpaceToView(userBtn,15)?.heightIs(MIDDLE_BTN_HEIGHT)?.rightSpaceToView(sbg,22)?.centerYEqualToView(sbg)
        
        sbg.addSubview(self.moreBtn)
        self.moreBtn.setImage(UIImage(named: "更多"), for: .normal)
        self.moreBtn.isHidden = true
        self.moreBtn.addTarget(self, action: #selector(moreBtnClick), for: .touchUpInside)
        let _ = self.moreBtn.sd_layout()?.widthIs(35)!.heightIs(35)!.rightSpaceToView(sbg,8)!.centerYEqualToView(sbg)
        
        
        return bg
        
    }()
    lazy var tableHeaderView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 90)
        bg.backgroundColor = UIColor.white
        
        let containerView = UIView()
        bg.addSubview(containerView)
        containerView.backgroundColor = UIColor.white
        var temp = Array<UIView>()
        let tits = ["行程路线","玩家产品","微社区","目的地"]
        
        for item in tits {
            
            let menuBtn = UIButton()
            menuBtn.setTitle(item, for: .normal)
            menuBtn.titleLabel?.font = UIFont.smallerFont
            menuBtn.titleLabel?.textAlignment = .center
            if item == "行程路线" {
                menuBtn.setImage(UIImage(named: "行程路线1"), for: .normal)

            }else if item == "玩家产品" {
                
                menuBtn.setImage(UIImage(named: "玩家产品01"), for: .normal)

            }
            else{
                menuBtn.setImage(UIImage(named: item), for: .normal)
            }
            menuBtn.setTitleColor(UIColor.textTitleColor, for: .normal)
            menuBtn.addTarget(self, action: #selector(menuClick), for: .touchUpInside)
            containerView.addSubview(menuBtn)
            let _ = menuBtn.sd_layout()?.heightIs(90)
            
            let _ = menuBtn.imageView?.sd_layout()?.widthIs(48)?.heightIs(48)?.topSpaceToView(menuBtn,6)?.centerXEqualToView(menuBtn)
            
            let _ = menuBtn.titleLabel?.sd_layout()?.heightIs(15)?.topSpaceToView(menuBtn.imageView,5)?.centerXEqualToView(menuBtn)?.widthRatioToView(menuBtn,1)
            
            
            temp.append(menuBtn)
            
        }
        let _ = containerView.sd_layout()?.topSpaceToView(bg,0)?.widthRatioToView(bg,1)
        
        containerView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 4, verticalMargin: 0, horizontalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        
        return bg
        
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white

        initViews()

        //获取当前经纬度
        XMLocationManager.share()?.requestAuthorization()
        XMLocationManager.share()?.startLocation()
        XMLocationManager.share()?.locationCompleteBlock = {coord in
            
            print("定位完成:\(coord)")
            
            self.coord = coord
            
            let region = MKCoordinateRegion(center: coord, span:  MKCoordinateSpan(latitudeDelta: 1.118404*0.26, longitudeDelta: 1.131468*0.26))
            
            self.mapview?.setRegion(region, animated: false)
            self.getCategorys()

            

        }

        //刷新token
//        if SPUtil.init().token.count > 0 {
//
//            API.updateToken(params: ["oldToken":SPUtil.init().token]) { (result) in
//
//                let login = result as! LoginResult
//                SPUtil.init().token = login.appToken
//            }
//            
//        }


    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    func initViews(){
        
        self.view.addSubview(self.contentView)
        self.contentView.addSubview(self.twoFloorView)
        self.contentView.addSubview(self.homeTableView)
        self.contentView.sd_y = -self.view.sd_height;
        self.view.addSubview(self.searchView)
        let _ = self.searchView.sd_layout()?.widthRatioToView(self.view,1)?.topSpaceToView(self.view,0)?.heightIs(HT_StatusBarAndNavigationBarHeight)
        
        //self.reloadMapMenus()
        sendRequest()
    
        
    }
    
    @objc func pullClick(){
        
        UIView.animate(withDuration: 0.4) {
            
            self.contentView.sd_y = -self.view.sd_height
            self.moreBtn.isHidden = true
            self.isShowedMap = false

            self.searBtn.setTitle("请输入目的地、线路", for: .normal)
            self.keywords = ""
            self.clearBtn?.isHidden = true
            let _ = self.searBtn.imageView?.sd_x = self.searBtn.center.x/2-35
            let _ = self.searBtn.titleLabel?.sd_x = self.searBtn.center.x/2-35+18
            let _ = self.searBtn.sd_layout()?.rightSpaceToView(self.sbg,22)!
            self.searBtn.updateLayout()
            self.lastMenuBtn = nil

        }
        
    }
    @objc func cardMaskClick(btn:UIButton){
        
        
        
        let cateVo = self.categorys.get(at: btn.tag-10086)
        
        if cateVo!.isActivity == true{
            
            if cateVo!.pdtId != nil{
                
                //跳转到产品详情
                API.playDetail(params: ["id":cateVo!.pdtId!]) { (result) in
                    
                    API.productCommentList(params: ["page":"1",
                                                    "pdtId":cateVo!.pdtId!]) { (pageVo) in
                        
                                                        
                                                        let page = pageVo as! Page<CommentVo>
                                                        let dvc = ProductDetailVC()
                                                        dvc.product = (result as! ProductVo)
                                                        if page.list.count > 0{
                                                            
                                                            dvc.commentVo = page.list.first
                                                        }
                                                        PUSH(from: self, to: dvc)
                    }
                    

                }
            }else{
                
                ToastUtil.show(msg: "暂无产品详情")
            }

            
            return
            
        }
        
        
        if cateVo?.type == "ROUTE"{
            
            let routevc = RouteViewController()
            routevc.curCategory = cateVo
            routevc.isOnlyOne = true
            PUSH(from: self, to: routevc)
            
        }else{
            
            API.home_category_detail(params: ["projectId":(cateVo?.id)!]) { (result) in
                 
                 
                 let dvc = PlaceDetailVC()
                 dvc.cateVo = (result as! CategoryVo)
                 PUSH(from: self, to: dvc)
                 
             }
        }

 

    }
    
    @objc func meClick(){
        
        if SPUtil.init().loginStatus == 0 {
            
            let vc = LoginViewController()
            PUSH(from: self, to: vc)
            return
        }
        PUSH(from: self, to: MeViewController())
    }
    @objc func menuClick(btn:UIButton){
        
        if btn.titleLabel?.text == "微社区"{
            
            
            PUSH(from: self, to: SocialViewController())
            
        }else if btn.titleLabel?.text == "玩家产品"{
            let dvc = ProductsViewController()
            dvc.recomArr = self.products
            PUSH(from: self, to: dvc)

        }else if btn.titleLabel?.text == "行程路线"{
            
            self.getCategorys()
            PUSH(from: self, to: RouteViewController())


        }else if btn.titleLabel?.text == "目的地"{
        
            self.contentView.sd_y = 0
            self.moreBtn.isHidden = false
            self.isClickPlace = true
            self.reloadMapMenus()
            self.isClickPlace = false
            self.isShowedMap = true
            self.mapTopMenuClick(btn: self.lastMenuBtn!)
        
            
            let _ = self.searBtn.sd_layout()?.rightSpaceToView(self.sbg,32+16)!
            self.searBtn.updateLayout()
        }
    }
    @objc func mapTopMenuClick(btn:UIButton){
        
        self.curClassisy = self.classy.get(at: btn.tag - 1900)

        
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 0.4))
        btn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)

        let icon = btn.viewWithTag(7979)
        icon?.isHidden = false
        
        if self.curClassisy?.name == "线路" {
            
            self.isHaveMore = true
            
            self.pageIndex = 1
            self.sendRequestForCategory(isShowAlert: true)
            let vc = RouteViewController()
            vc.keywords = self.keywords
            PUSH(from: self, to: vc)

            
        }else{
            
            let time: TimeInterval = 1.0
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                //code
                print("1 秒后输出")


            }
            self.isHaveMore = true
            self.pageIndex = 1
            self.sendRequestForCategory(isShowAlert: true)
            

        }

        
        if lastMenuBtn != btn {
            
            let icon = lastMenuBtn!.viewWithTag(7979)
            icon?.isHidden = true
            lastMenuBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            lastMenuBtn?.setTitleColor(UIColor.init(hexString: "#999999"), for: .normal)
        }
        
        
        lastMenuBtn = btn
        
    }

    @objc func moreBtnClick(){
        

        let popView = PopoverView.init()
        var actions: Array<PopoverAction> = [PopoverAction]()
         for item in ["行程路线","玩家产品","微社区","目的地"] {
             
             let action = PopoverAction.init(title: item) { (action) in
                 
                self.moreBtn.setImage(UIImage(named: "更多"), for: .normal)
                self.moreBtn.isSelected = false

                let vo = action?.model as! String
                
                if vo == "微社区"{
                    
                    PUSH(from: self, to: SocialViewController())
                    
                }else if vo == "行程路线"{
                    
                    PUSH(from: self, to: RouteViewController())

                }else if vo == "玩家产品"{
                    
                    let dvc = ProductsViewController()
                    dvc.recomArr = self.products
                    PUSH(from: self, to: dvc)
                    
                }else{
                    
     
                    self.isClickPlace = true
                    self.reloadMapMenus()
                    self.isClickPlace = false
                    self.mapTopMenuClick(btn: self.lastMenuBtn!)

                }
                 
                 
                 
             }
             action?.model = item
             actions.append(action!)
             
         }
         popView.hideAfterTouchOutside = true
         popView.style = .default
        popView.showShade = true
         popView.show(to: moreBtn, with: actions)


        

    }
    
    @objc func startSearchClick(){
        
        let searVC = PYSearchViewController.init(hotSearches: ["杭州2日小众路线","厦门2日游","西安经典3日游","苏州","上海"], searchBarPlaceholder: "请输入目的地、线路") { (vc, bar, str) in
            

            vc?.dismiss(animated: true, completion: {
                
            })
            if str?.isEmpty == true{
                
                ToastUtil.show(msg: "请输入搜索内容")
                return
            }
            self.clearBtn?.isHidden = false
            self.keywords = str!
            self.contentView.sd_y = 0
            self.moreBtn.isHidden = false
            self.isShowedMap = true
            self.isClickSearch = true
            self.searBtn.setTitle(self.keywords, for: .normal)
            self.pageIndex = 1
            
            self.sendRequestForCategory(isShowAlert: true)

            
            let _ = self.searBtn.sd_layout()?.rightSpaceToView(self.sbg,32+16)!
            self.searBtn.updateLayout()
            
            let _ = self.searBtn.imageView?.sd_x = 16
            let _ = self.searBtn.titleLabel?.sd_x = 35
            
            
            
            
        }
        let nav = UINavigationController(rootViewController: searVC!)
        self.present(nav, animated: true) {
            
            
        }
        
    }
   
}

extension HomeViewController:UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UITextFieldDelegate{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let mod = self.dataArray.get(at: indexPath.row)
        //微社区
        if mod is Array<TopPic> {
            
            let arr = mod as! Array<TopPic>
            
            if arr.count > 3{
                
                return 300+65
                
            }else{
                
                return CGFloat(arr.count*100+65)

            }
            
        }else if mod is RouteVo || mod is ScenicVo{
            
            return 265-145+(KScreenWidth-50)*9/16
            
        }else{
            
            return 255-20-145+(KScreenWidth-50)*9/16

        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 90
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return self.tableHeaderView
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let mod = self.dataArray.get(at: indexPath.row)
        
        
        
        if mod is RouteVo {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "LineCell") as! LineCell
            cell.setModel(mod: self.dataArray.get(at: indexPath.row) as! RouteVo)
            return cell
            
        }else if mod is ScenicVo{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "LineCell") as! LineCell
            cell.setScenic(mod: self.dataArray.get(at: indexPath.row) as! ScenicVo)
            return cell
        }
        else if mod is Array<TopPic>{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "WeSocialCell") as! WeSocialCell
            cell.setModel(topics: self.dataArray.get(at: indexPath.row) as! Array<TopPic>)
            cell.gotoScail = {
                
                PUSH(from: self, to: SocialViewController())
            }
            cell.topicBtnClick = {topic in
                
                API.socialDetail(params: ["pId":topic.id!]) { (result) in
                    
                    
                    let dvc = SocialDetailVC()
                    dvc.topPic = (result as! TopPic)
                    PUSH(from: self, to: dvc)
                }
                
   
            }
            return cell
            
        }else if mod is ProductVo{
            
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "GoodsCell") as! GoodsCell
            cell.setModel(mod: self.dataArray.get(at: indexPath.row) as! ProductVo)
            return cell
            
        }else{
            
            return UITableViewCell()
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let mod = self.dataArray.get(at: indexPath.row)
        

        
        if mod is RouteVo {
            
            
            let mods = self.dataArray.get(at: indexPath.row) as! RouteVo
            let cateVo = CategoryVo()
            cateVo.id = mods.id
            cateVo.proName = mods.proName
            let routevc = RouteViewController()
            routevc.curCategory = cateVo
            routevc.isOnlyOne = true
            PUSH(from: self, to: routevc)

        }else if mod is Array<TopPic>{
            
            
            
        }else if mod is ScenicVo{
            
            let mod = self.dataArray.get(at: indexPath.row) as! ScenicVo

            API.home_category_detail(params: ["projectId":mod.id!]) { (result) in
                 
                 
                 let dvc = PlaceDetailVC()
                 dvc.cateVo = (result as! CategoryVo)
                 PUSH(from: self, to: dvc)
                 
             }
        }
        else{
            
            let mod = self.dataArray.get(at: indexPath.row) as! ProductVo
            API.playDetail(params: ["id":mod.id!]) { (result) in
                
                
                API.productCommentList(params: ["page":"1",
                                                "pdtId":mod.id!]) { (pageVo) in
                    
                                                    
                                                    let page = pageVo as! Page<CommentVo>
                                                    let dvc = ProductDetailVC()
                                                    dvc.product = (result as! ProductVo)
                                                    if page.list.count > 0{
                                                        
                                                        dvc.commentVo = page.list.first
                                                    }
                                                    PUSH(from: self, to: dvc)
                }
                
                
            }
        
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let yOffset = scrollView.contentOffset.y
        if scrollView == self.homeTableView {
            
            if yOffset <= -25 {

                self.displayLabel.text = "下拉进入地图页面"
            }
            if yOffset <= -40 {

                self.displayLabel.text = "继续下拉进入地图页面,松手刷新数据"
            }
            if yOffset <= -60 {

                self.displayLabel.text = "松手进入地图页面"
            }
        }
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        let yOffset = scrollView.contentOffset.y
        if scrollView == self.homeTableView {
            
            if yOffset <= -60 {
                
                UIView.animate(withDuration: 0.4, animations: {
                    
                    self.contentView.sd_y = 0
                    self.moreBtn.isHidden = false
                    self.isShowedMap = true

                    let _ = self.searBtn.sd_layout()?.rightSpaceToView(self.sbg,32+16)!
                    self.searBtn.updateLayout()
                    

                    

                }) { (finish) in
                    
                }
            }
            if yOffset <= -40{
                
                self.dataArray.removeAll()
                self.sendRequest()
                self.pageIndex = 1
                self.getCategorys()
                API.activityProducts(params: [:]) { (result) in
                    
                    let arr = (result as! Array<ActivisProduct>)
                    SPUtil.init().activits = arr.toJSONString()
                }
            }
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        if scrollView == mapbg {
         
            self.isNeedReloadData = false
            let page  = scrollView.contentOffset.x/(scrollView.bounds.width)
            print("page==\(page)")

            let tempPage =  Int(round(page))

            let mod = self.categorys.get(at: tempPage)
            self.curMod = mod
            
            for item in self.categorys {
                
                item.isSelect = false
                
            }
            if mod?.isActivity == false{
                
                mod?.isSelect = true

            }

            showAntions(arr: self.categorys)
     
            if mod != nil {
                
                let coordinate = CLLocationCoordinate2D(latitude: Double((mod?.latitude)!)!, longitude: Double((mod?.longitude)!)!)
                let region = MKCoordinateRegion(center: coordinate, span:  MKCoordinateSpan(latitudeDelta: 2.118404*0.01, longitudeDelta: 2.131468*0.01))
                self.mapview?.setRegion(region, animated: false)
                self.coord = coordinate
            }
            

            let actinums = self.getActivisGoods().count
            
            if tempPage == self.categorys.count-1-actinums && self.isHaveMore == true{
                
                self.pageIndex = self.pageIndex+1
                self.sendRequestForCategory(isShowAlert: true)
                
            }
            if self.isHaveMore == false && tempPage == self.categorys.count-1 - actinums {
                
                ToastUtil.show(msg: "没有更多数据了")
                self.isHaveMore = false

            }
            

        }
        

    }
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        

        
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        
    }

}
extension HomeViewController:MKMapViewDelegate{
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        
        if annotation .isKind(of: LSListAnnotation.self) {
            
            let ann = annotation as! LSListAnnotation
            let mod = ann.model as! CategoryVo
            
            if mod.isActivity == false{
                
                let mod = ann.model as! CategoryVo
                
                
                
                let pointReuseIndetifier = "pointReuseIndetifier"
                var annotationView = mapview?.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
                if annotationView == nil{
                    
                    annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
                    annotationView?.canShowCallout = true
                    
                    let btn = UIButton(type: .infoLight)
                    btn.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
                    btn.addTarget(self, action: #selector(annDetailClick), for: .touchUpInside)
                    annotationView?.rightCalloutAccessoryView = btn
                }
                
                if mod.isSelect == true {
                    
                    annotationView?.image = UIImage(named: "place_ed")

                }else{
                    
                    annotationView?.image = UIImage(named: "map_def")

                }
                return annotationView

            }else{
                
                let pointReuseIndetifier = "pointReuseIndetifier11"
                var annotationView = mapview?.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
                if annotationView == nil{
                    
                    annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
                    annotationView?.canShowCallout = true
                    
                    let btn = UIButton(type: .infoLight)
                    btn.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
                    btn.addTarget(self, action: #selector(annDetailClick), for: .touchUpInside)
                    annotationView?.rightCalloutAccessoryView = btn
                }
                let url = URL(string: mod.iconUrl!)
                
                let img = SDImageCache.shared.imageFromDiskCache(forKey: mod.iconUrl?.split(string: "/").last)
                if img == nil{
                    
                    
                    DispatchQueue.global().async {//并行、异步
                        
                        var image: UIImage?
                        do {
                             let data = try Data(contentsOf: url!)
                            image = UIImage(data: data)
                            SDImageCache.shared.store(image, imageData: data, forKey: mod.iconUrl?.split(string: "/").last, toDisk: true) {
                                
                            }

                         }catch let error as NSError {
                             print(error)
                            
                         }
                        DispatchQueue.main.async {//串行、异步
                            
                            annotationView?.image = image?.scaleTo(w: 35, h: 35)
                        }
                    }
                    
                }else{
                    
                    
                    annotationView?.image = img!.scaleTo(w: 35, h: 35)
                }

                return annotationView

            }

        }
        return nil
    }
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        
        
        print("regin-lat\(mapView.region.span.latitudeDelta) regin-longt\(mapView.region.span.longitudeDelta)")
        
        if self.lastMenuBtn?.titleLabel?.text == "线路" {
            
            return
        }
        
        if self.coord != nil {
            
            let distance:Double = (XMLocationManager.share()?.customDistance(withEnd: mapView.region.center, fromStart: self.coord!))!
            
            if distance >= 200000.00 && self.isShowedMap == true && self.isNeedReloadData == true{ //有问题再改最后一个条件//self.isHaveMore==true
                
                self.coord = mapView.region.center
                self.sendRequestForCategory(isShowAlert: false)
                
            }
            self.isNeedReloadData = true
        }
        
    }
    @objc func annDetailClick(){
        
        let cateVo = self.curMod
        if self.curMod?.isActivity == true{
            
            if self.curMod?.pdtId != nil{
                
                //跳转到产品详情
                API.playDetail(params: ["id":self.curMod!.pdtId!]) { (result) in
                    
                    API.productCommentList(params: ["page":"1",
                                                    "pdtId":self.curMod!.pdtId!]) { (pageVo) in
                        
                                                        
                                                        let page = pageVo as! Page<CommentVo>
                                                        let dvc = ProductDetailVC()
                                                        dvc.product = (result as! ProductVo)
                                                        if page.list.count > 0{
                                                            
                                                            dvc.commentVo = page.list.first
                                                        }
                                                        PUSH(from: self, to: dvc)
                    }
                    

                }
            }else{
                
                ToastUtil.show(msg: "暂无产品详情")
            }

            
            return
            
        }
        
        if cateVo!.type == "ROUTE"{
            
            let routevc = RouteViewController()
            routevc.curCategory = cateVo
            routevc.isOnlyOne = true
            PUSH(from: self, to: routevc)
            
        }else{
            
            API.home_category_detail(params: ["projectId":(cateVo!.id)!]) { (result) in
                 
                 
                 let dvc = PlaceDetailVC()
                 dvc.cateVo = (result as! CategoryVo)
                 PUSH(from: self, to: dvc)
                 
             }
        }
        
    }
    
    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        
        if view.annotation is MKUserLocation{
            
            return
        }
        
        
        for item in self.categorys{
            
            item.isSelect = false
            
        }
        
        let ann = view.annotation as! LSListAnnotation
        
        let mod = ann.model as! CategoryVo
        if mod.isActivity == false {
            
            mod.isSelect = true

        }
        
        
        if mod.id == self.curMod!.id{
            
            
        }else{
            
            
            self.showAntions(arr: self.categorys)

        }

        let index = (self.categorys as NSArray).index(of: mod)

        let coordinate = CLLocationCoordinate2D(latitude: Double((mod.latitude)!)!, longitude: Double((mod.longitude)!)!)
        self.coord = coordinate
        let region = MKCoordinateRegion(center: coordinate, span:  MKCoordinateSpan(latitudeDelta: 2.118404*0.01, longitudeDelta: 2.131468*0.01))
        self.mapview?.setRegion(region, animated: false)
        
        self.curMod = mod
        //scr 滚动
        mapbg?.setContentOffset(CGPoint(x: CGFloat(index)*(twoFloorView.width-40), y: 0), animated: true)
    
        
    
        
    }
    
    func showAntions(arr:Array<CategoryVo>){
        
        if self.currentArr.count > 0{
            
            self.mapview!.removeAnnotations(self.currentArr)
        }
        self.currentArr.removeAll()
        


        if self.firstMod == nil {
            
            self.firstMod = arr.first
            self.firstMod?.isSelect = true
            self.curMod = arr.first
        }

        
        for item in arr {
            
//            let latlongt = BZHttpFileHelper.baiduToGaode(withLat: Double(item.latitude!)!, longt: Double(item.longitude!)!)
//            let lat = latlongt.split(string: ",").first
//            let longt = latlongt.split(string: ",").last

            let ann = LSListAnnotation(coordinates: CLLocationCoordinate2D(latitude: Double(item.latitude!)!, longitude: Double(item.longitude!)!), title: item.proName, subTitle: item.proAddress)
            ann?.model = item
            if self.curAnn == nil{
                
                self.curAnn = ann
            }
            
            self.mapview?.addAnnotation(ann!)
            if item.isActivity == false {
                
                self.currentArr.append(ann!)

            }
            
        }
        
        
        let mod = arr.first
        let firstAnn = self.currentArr.first
        let coordinate = firstAnn?.coordinate
        if mod?.isActivity == false {
            
            self.mapview?.setCenter(coordinate!, animated: false)

        }

    }
    @objc func backToUser(){
        
        
        let coordinate = CLLocationCoordinate2D(latitude: XMLocationManager.share()!.latitude,longitude: XMLocationManager.share()!.longitude )
        let region = MKCoordinateRegion(center: coordinate, span:  MKCoordinateSpan(latitudeDelta: 2.118404*0.1, longitudeDelta: 2.131468*0.1))
        self.mapview?.setRegion(region, animated: false)
        
        searBtn.setTitle("请输入目的地、线路", for: .normal)
        self.keywords = ""
        self.clearBtn?.isHidden = true

        let _ = self.searBtn.imageView?.sd_x = self.searBtn.center.x/2-35
        let _ = self.searBtn.titleLabel?.sd_x = self.searBtn.center.x/2-35+18


        
    }
    @objc func clearBtnClick(){
        
        searBtn.setTitle("请输入目的地、线路", for: .normal)
        self.keywords = ""
        self.clearBtn?.isHidden = true
        let _ = self.searBtn.imageView?.sd_x = self.searBtn.center.x/2-35
        let _ = self.searBtn.titleLabel?.sd_x = self.searBtn.center.x/2-35+18
        
    }
    
    func isLocationServiceOpen() -> Bool {
        if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.denied {
            return true
        } else {
            return false
        }
    }

}
